package com.fengba.nanzhi.tabbar04.wz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.airsaid.pickerviewlibrary.CityPickerView;
import com.airsaid.pickerviewlibrary.listener.OnSimpleCitySelectListener;
import com.bumptech.glide.Glide;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class BjAdderssActivity extends AppCompatActivity {
    private TextView mTextdzxzsr,mTextsjrsr,mTextlxdhsr,mTextxxdzsr;
    private Button mBtnbc;
    private ImageButton mBtnxzdz;
    private Switch mSwitch;
    private String province="";
    private String city="";
    private String district="";
    private int mrdzcz;
    private String id;
    private String user_id,province1,city1,district1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wz_activity_bj_adderss);
        mTextdzxzsr = findViewById(R.id.dzxzsr);//地址选择
        mTextsjrsr = findViewById(R.id.sjrsr);//收件人姓名
        mTextlxdhsr = findViewById(R.id.lxdhsr);//联系电话
        mTextxxdzsr = findViewById(R.id.xxdzsr);//详细地址
        mSwitch = findViewById(R.id.mrdzkg);//默认地址开关
        getUserId();
        JSONObject jsonObject = null;
        String js =  getIntent().getStringExtra("bjdz");

        if(js!=null){
            try {
                jsonObject= new JSONObject(js);
                id = jsonObject.get("id").toString().trim();
                String receiver_name = jsonObject.get("receiver_name").toString();
                String receiver_phone = jsonObject.get("receiver_phone").toString();
                province1 = jsonObject.get("province").toString();
                city1 = jsonObject.get("city").toString();
                district1 = jsonObject.get("district").toString();
                String address = jsonObject.get("address").toString();
                String isdefault = jsonObject.get("isdefault").toString();
                if(isdefault.equals("1")) {
                    mSwitch.setChecked(true);
                }

               // Toast.makeText(BjAdderssActivity.this, js, Toast.LENGTH_SHORT).show();
                mTextsjrsr.setText(receiver_name);
                mTextlxdhsr.setText(receiver_phone);
                mTextxxdzsr.setText(address);
                mTextdzxzsr.setText(province1+""+city1+""+district1+"");


                mBtnbc = findViewById(R.id.bjdzbc);
                mBtnbc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if(mTextsjrsr.length()==0){
                            Toast.makeText(BjAdderssActivity.this,"请输入收件人姓名",Toast.LENGTH_SHORT).show();
                        }else if(mTextlxdhsr.length()==0){
                            Toast.makeText(BjAdderssActivity.this,"请输入联系电话",Toast.LENGTH_SHORT).show();
                        }else if(mTextdzxzsr.length()==0){
                            Toast.makeText(BjAdderssActivity.this,"请选择地址",Toast.LENGTH_SHORT).show();
                        }else if(mTextxxdzsr.length()==0){
                            Toast.makeText(BjAdderssActivity.this,"请输入详细地址",Toast.LENGTH_SHORT).show();
                        }else if(!isMobile((String) mTextlxdhsr.getText().toString())){
                            Toast.makeText(BjAdderssActivity.this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
                        }else{

                            if(mSwitch.isChecked()){
                                mrdzcz = 1;
                            }else{
                                mrdzcz = 0;
                            }
                            if(city.trim().equals("1")){
                                city = "";
                            }else if(city.trim().equals("")){
                                city = city1;
                            }
                            if(district.trim().equals("")){
                                district=district1;
                            }
                            if(province.trim().equals("")){
                                province=province1;
                            }
                            showToast(BjAdderssActivity.this,mrdzcz+"");
                            OKManager.getInstance().type1021(id.trim(), user_id,mTextsjrsr.getText().toString().trim(), mTextlxdhsr.getText().toString().trim(), province, city, district, mTextxxdzsr.getText().toString().trim(), String.valueOf(mrdzcz), new OKManager.func4() {
                                @Override
                                public void onResponse(JSONObject jsonObject) {
                                    try {

                                        finish();
                                        if (jsonObject.get("code").toString().trim().equals("0")) {
                                            Intent intent = new Intent(BjAdderssActivity.this, AddressActivity.class);
                                            startActivity(intent);
                                            intent.putExtra("xianshi", 1);
                                        }else{
                                            showToast(BjAdderssActivity.this,jsonObject.get("message").toString());
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onFailure(String string) {
                                    showToast(BjAdderssActivity.this,"网络错误");
                                }
                            });
                        }

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }else{
            mBtnbc = findViewById(R.id.bjdzbc);
            mBtnbc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if(mTextsjrsr.length()==0){
                        Toast.makeText(BjAdderssActivity.this,"请输入收件人姓名",Toast.LENGTH_SHORT).show();
                    }else if(mTextlxdhsr.length()==0){
                        Toast.makeText(BjAdderssActivity.this,"请输入联系电话",Toast.LENGTH_SHORT).show();
                    }else if(mTextdzxzsr.length()==0){
                        Toast.makeText(BjAdderssActivity.this,"请选择地址",Toast.LENGTH_SHORT).show();
                    }else if(mTextxxdzsr.length()==0){
                        Toast.makeText(BjAdderssActivity.this,"请输入详细地址",Toast.LENGTH_SHORT).show();
                    }else if(!isMobile((String) mTextlxdhsr.getText().toString())){
                        Toast.makeText(BjAdderssActivity.this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
                    }else{
                        if(city.trim().equals("1")){
                            city = "";
                        }
                        if(mSwitch.isChecked()){
                            mrdzcz = 1;
                        }else{
                            mrdzcz = 0;
                        }

                        OKManager.getInstance().type1020(user_id, String.valueOf(mTextsjrsr.getText().toString()), String.valueOf(mTextlxdhsr.getText().toString()), String.valueOf(province), String.valueOf(city), String.valueOf(district), String.valueOf(mTextxxdzsr.getText().toString()), String.valueOf(mrdzcz), new OKManager.func4() {
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    if (jsonObject.get("code").toString().trim().equals("0")) {
                                        finish();
                                        Intent intent = new Intent(BjAdderssActivity.this, AddressActivity.class);
                                        intent.putExtra("xianshi", 0);
                                        startActivity(intent);
                                    }else{
                                        showToast(BjAdderssActivity.this,jsonObject.get("message").toString());
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(String string) {
                                showToast(BjAdderssActivity.this,"网络错误");
                            }
                        });

                    }

                }
            });
        }
        //隐藏title



        mTextlxdhsr.setInputType(EditorInfo.TYPE_CLASS_PHONE);

        //关闭页面
        mBtnxzdz = findViewById(R.id.Bjshdzfh);
        mBtnxzdz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTextdzxzsr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseArea(mTextdzxzsr);
            }
        });


    }

    //Texview的点击事件
    public void chooseArea(View view) {
        //判断输入法的隐藏状态
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
            selectAddress();//调用CityPicker选取区域

        }

    }

    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    private void selectAddress() {
        CityPickerView mCityPickerView = new CityPickerView(this);
        // 设置点击外部是否消失
//        mCityPickerView.setCancelable(true);
        // 设置滚轮字体大小
//        mCityPickerView.setTextSize(18f);
        // 设置标题
//        mCityPickerView.setTitle("我是标题");
        // 设置取消文字
//        mCityPickerView.setCancelText("我是取消文字");
        // 设置取消文字颜色
//        mCityPickerView.setCancelTextColor(Color.GRAY);
        // 设置取消文字大小
//        mCityPickerView.setCancelTextSize(14f);
        // 设置确定文字
//        mCityPickerView.setSubmitText("我是确定文字");
        // 设置确定文字颜色
//        mCityPickerView.setSubmitTextColor(Color.BLACK);
        // 设置确定文字大小
//        mCityPickerView.setSubmitTextSize(14f);
        // 设置头部背景
//        mCityPickerView.setHeadBackgroundColor(Color.RED);
        mCityPickerView.setOnCitySelectListener(new OnSimpleCitySelectListener(){
            @Override
            public void onCitySelect(String prov, String city2, String area) {

                if(city2!=null&&!city2.trim().equals("")) {
                    mTextdzxzsr.setText("省: " + prov + "   市: " + city2 + "   区: " + area);
                    Toast.makeText(BjAdderssActivity.this,"省: " + prov + " 市: " + city2 + " 区: " + area,Toast.LENGTH_SHORT).show();
                    province = prov;
                    city = city2;
                    district = area;
                }else{
                    mTextdzxzsr.setText("省: " + prov + "   区: " + area);
                    province = prov;
                    district = area;
                    city = "1";
                }
            }
            @Override
            public void onCitySelect(String str) {
                // 一起获取

            }
        });
        mCityPickerView.show();
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobile(String number) {
    /*
    移动：134、135、136、137、138、139、150、151、152、157(TD)、158、159、178(新)、182、184、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、170、173、177、180、181、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String num = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[34578]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(number)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return number.matches(num);
        }
    }
    public void getUserId(){
        Object user_info = Preferences.getParam(BjAdderssActivity.this,"user_info","");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());

            //账号
            user_id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
